import React, { useCallback, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'

import { NavBar, Icon } from 'antd-mobile'

import { actionCreator } from '../home/cookbook'

import { ListWrap, SubTitle, ListContainer } from './StyledList'
import animate from '../hoc/animate'


const List = (props) => {
  
  const list = useSelector(state => state.getIn(['cookbook', 'list']))
  const history = useHistory()
  const location = useLocation()
  const dispatch = useDispatch()

  useEffect(() => {
    if (list.length === 0) {
      dispatch(actionCreator.loadDataSyncSaga())
    }
  },[dispatch, list])


  const handleClickLeft = useCallback(
    () => {

      history.push('/home')
    },[history]
  )

  const handleGotoDetail = useCallback(
    (title) => {
      return () => {
        history.push('/detail', { title })
      }
    },[history, location]
  )

  let state = location.state
  return (
    <ListContainer>
      <NavBar
        icon={<Icon type='left' />}
        onLeftClick={handleClickLeft}
        style={{ backgroundColor: '#ee742f' }}
      >
        {state && state.title}
      </NavBar>
      <ul>

        {
          list.map((item, i) => (
            <ListWrap onClick={handleGotoDetail(item.name)} width='0 0 1px 0' key={item.name + i}>
              <div>
                <img src={item.img} width='115' height='75' alt="" />
              </div>
              <div>
                <h1>{item.name}</h1>
                <SubTitle>{item.burdens}</SubTitle>
                <h3>{item.all_click}收藏 {item.favorites}浏览</h3>
              </div>
            </ListWrap>
          ))
        }



      </ul>
    </ListContainer>
  )
}

export default animate(List)